﻿#pragma once
// Copyright (c) lanyeo 2020-2021
// Licenced under MIT license. See https://opensource.org/licenses/MIT for details.
// code style
// 1. use forward declaration (尽可能使用前置声明)
// 2. include file sequence [other project>c>c++>third>self project]
// 

#include <util/fist-time-inl.h>

#include <asio.hpp>

#include "network_interface.h"


class CNetworkNode;
class CNetworkConfParser;

class CNetworkManager : public INetworkManager
{
    MANAGER_INFO(INetworkManager)

    static constexpr uint32_t CHECK_INVALID_CONNECT_TIME = 5 * 1000;
public:

    explicit CNetworkManager();
    ~CNetworkManager() override;
    bool Init() override;
    void Update() override;
    void Destroy() override;
private:
    void Run() override;
    void CreateAccept();
    bool RegisterRawPackHandle(int type, IRawPackHandlerManager* manager) override;
    void ProcMessage(int type, netlink_t link, const std::string& msg) override;
    netlink_t AddConnect(const std::string& ip, uint16_t port, uint32_t timeout) override;
    int SendOneMessage(netlink_t link, const std::string& msg) override;
    const NetworkConf* cfg() override;
    void CheckInvalidConnect();
private:
    asio::io_service* m_service;
    asio::ip::tcp::acceptor* m_acceptor;
    std::thread* m_server_run;
    bool m_server_running;
    std::map<netlink_t, CNetworkNode*> m_nodes;
    CNetworkConfParser* m_cfg_parser;
    fist::ms_t m_check_invalid_connect;
    std::unordered_map<int, IRawPackHandlerManager*> m_pack_handlers;
};
